package com.stn.zjx.givingtreasure.activity.scan;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.base.BaseActivity;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.event.ScanResultEvent;
import com.stn.zjx.givingtreasure.utils.StatusBarUtil;
import com.stn.zjx.givingtreasure.utils.ToolsUtils;
import com.vondear.rxtools.RxPhotoTool;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zxing.QRCodeDecoder;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;


public class StoreScanActivity extends BaseActivity implements QRCodeView.Delegate {
    public static final int TRANSTER = 101;
    private static final int PRC_PHOTO_PICKER = 111;
    @BindView(R.id.zbarview)
    QRCodeView zbarview;

    public boolean isFalash = false;
    public int flag = 0;
    @BindView(R.id.back_bt)
    RelativeLayout backBt;
    @BindView(R.id.flash_bt)
    RelativeLayout flashBt;
    @BindView(R.id.open_img_bt)
    RelativeLayout openImgBt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_store_scan);
        flag = getIntent().getIntExtra("flag", 0);
        ButterKnife.bind(this);
        initComponent();
        zbarview.setDelegate(this);
        methodRequiresTwoPermission();

    }

    @Override
    protected void onStart() {
        super.onStart();
        zbarview.startCamera();
//        mQRCodeView.startCamera(Camera.CameraInfo.CAMERA_FACING_FRONT);
        zbarview.showScanRect();
        zbarview.startSpot();

    }

    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }


    @Override
    protected void onStop() {
        zbarview.stopCamera();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        zbarview.onDestroy();
        super.onDestroy();
    }


    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
        MediaPlayer mPlayer = MediaPlayer.create(this, R.raw.scan_music);
        mPlayer.start();
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        vibrate();
        zbarview.startSpot();
        if (TextUtils.isEmpty(result)) {
            showToast(getString(R.string.scan_erwei_not_find_content));
        }
        ScanResultEvent  event=new ScanResultEvent();
        event.flag=flag;
        event.data=result;
        EventBus.getDefault().post(event);
        finish();

    }


    @Override
    public void onScanQRCodeOpenCameraError() {

        showToast(getString(R.string.open_camera_error));
    }

    /**
     * 发送请求权限
     */
    @AfterPermissionGranted(REQUEST_PERMISSION)
    public void methodRequiresTwoPermission() {
        //相机，存储，定位，网络状态
        String[] perms = {Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_NETWORK_STATE
        };
        //是否有以上权限
        if (EasyPermissions.hasPermissions(this, perms)) {

        } else {
            //发起请求权限
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, getString(R.string.request_perssion_desc),
                    REQUEST_PERMISSION, perms);
        }
    }
    @AfterPermissionGranted(PRC_PHOTO_PICKER)
    public void choicePhoto(int openType) {
        String[] perms = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
            switch (openType){
                case 0:
                    RxPhotoTool.openCameraImage(this);
                    break;
                case 1:
                    RxPhotoTool.openLocalImage(this);
                    break;
            }

        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.request_perssion_desc), PRC_PHOTO_PICKER, perms);
        }
    }
    @Override
    public void initComponent() {
        initStatusBarColor(R.color.transparentBlank_5);
        StatusBarUtil.setImmersiveStatusBar(this, false);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION) {
            zbarview.startCamera();
            zbarview.showScanRect();
            zbarview.startSpot();
        }
    }

    @OnClick({R.id.back_bt, R.id.flash_bt, R.id.open_img_bt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_bt:
                finish();
                break;
            case R.id.flash_bt:
                if(isFalash){
                    zbarview.closeFlashlight();
                    isFalash=false;
                    flashBt.setBackgroundResource(R.drawable.circle_black_self);
                }else{
                    zbarview.openFlashlight();
                    isFalash=true;
                    flashBt.setBackgroundResource(R.drawable.circle_qianblue);
                }
                break;
            case R.id.open_img_bt:
                choicePhoto(1);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case RxPhotoTool.GET_IMAGE_FROM_PHONE://选择相册之后的处理
                if(data.getData()   ==null){
                    return;
                }
                Glide.with(StoreScanActivity.this)
                        .asBitmap()
                        .load(data.getData())
                        .into(new SimpleTarget<Bitmap>() {
                            @SuppressLint({"StaticFieldLeak", "CheckResult"})
                            @Override
                            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                              Bitmap   newBitmap=ToolsUtils.comp(resource);
                                Observable.create(new ObservableOnSubscribe<String>() {
                                    @Override
                                    public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                                        String result=QRCodeDecoder.syncDecodeQRCode(newBitmap);
                                         if(!TextUtils.isEmpty(result)){
                                             emitter.onNext(result);
                                         }else{
                                             emitter.onNext("");
                                         }

                                    }
                                }).subscribeOn(Schedulers.newThread())
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .doOnSubscribe(new Consumer<Disposable>() {
                                            @Override
                                            public void accept(Disposable disposable) throws Exception {
                                                  showLoading();
                                            }
                                        })
                                        .doOnComplete(new Action() {
                                            @Override
                                            public void run() throws Exception {
                                                if(!isFinishing()){
                                                    dissmissLoading();
                                                }
                                            }
                                        })
                                        .subscribe(new Consumer<String>() {
                                            @Override
                                            public void accept(String result) throws Exception {
                                                  if(TextUtils.isEmpty(result)){
                                                      showToast(getString(R.string.scan_erwei_not_find_content));
                                                      finish();
                                                  }
                                                ScanResultEvent  event=new ScanResultEvent();
                                                  event.flag=flag;
                                                  event.data=result;
                                                  EventBus.getDefault().post(event);
                                                finish();
                                            }
                                        });

                            }
                        });


                break;
        }
    }

}
